/*

@Author:李朝晖

@Date: 2018-12-12

@Last Modified time: 2018-12-16
*/
import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';
import { Observable } from 'rxjs';
import { AuthService } from '../service/auth.service';
provide: [AuthService]
@Injectable({
  providedIn: 'root'
})
export class AuthGuard implements CanActivate {
  constructor(private router: Router) { }

  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): boolean {
    let url: string = state.url;
    // return true;
    return this.checkLogin(url);
  }

  checkLogin(url: string): boolean {
    if (AuthService.getUserId() != 0) {
      if (url.startsWith("/staff")) {
        if (AuthService.getPosition() == "员工") {
          return true;
        } else {
          this.router.navigate(['/staff']);
          return false;
        }
      } else if (url.startsWith("/administrative")) {
        if (AuthService.getPosition() == "行政人员") {
          return true;
        } else {
          this.router.navigate(['/administrative']);
          return false;
        }
      } else if (url.startsWith("/manager")) {
        if (AuthService.getPosition() == "部门经理" ||
          AuthService.getPosition() == "副总经理" ||
          AuthService.getPosition() == "总经理") {
          return true;
        } else {
          this.router.navigate(['/manager']);
          return false;
        }
      }

      return true;
    } else {
      //否则重定向到login
      this.router.navigate(['/login']);
      return false;
    }


  }
}
